import { Injectable, ExecutionContext, CanActivate, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { PUBLIC_KEY } from '../../common/contants/decorator.contant';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private reflector: Reflector) {
    super();
  }

  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    // 检查路由是否标记为公开
    const noInterception = this.reflector.getAllAndOverride(PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    
    // 如果是公开路由，直接通过
    if (noInterception) {
      return true;
    }
    console.log('JwtAuthGuard canActivate');
    // 否则执行正常的JWT认证
    return super.canActivate(context);
  }

   /* 主动处理错误 */
  handleRequest(err, user, info) {
    // 处理不同类型的JWT错误
    if (info?.name === 'TokenExpiredError') {
      throw new UnauthorizedException('登录令牌已过期，请重新登录')
    } else if (info?.name === 'JsonWebTokenError') {
      throw new UnauthorizedException('无效的登录令牌')
    } else if (err || !user) {
      throw err || new UnauthorizedException('登录状态已过期或无效')
    }
    return user
  }
}
